<template>
  <div class="dashboard-wrapper">
    <div class="dashboard-container">
      <!-- 顶部导航栏 -->
      <div class="dashboard-header">
        <div class="header-left">
          <h1>用户控制台</h1>
        </div>
        <div class="header-right">
          <div class="user-info" @click="toggleUserMenu">
            <div class="user-avatar">
              {{ user.username?.charAt(0).toUpperCase() || 'U' }}
            </div>
            <span class="username">{{ user.username }}</span>
            <i class="fas fa-chevron-down"></i>
          </div>
          
          <!-- 用户菜单 -->
          <div v-if="userMenuVisible" class="user-menu">
            <div class="menu-item" @click="manageProfile">
              <i class="fas fa-user"></i>
              <span>个人资料</span>
            </div>
            <div class="menu-item" @click="handleLogout">
              <i class="fas fa-sign-out-alt"></i>
              <span>退出登录</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="welcome-section">
        <h2>欢迎回来，{{ user.username }}！</h2>
        <p>今天是 {{ getCurrentDate() }}，让我们一起完成更多任务吧！</p>
      </div>
      
      <!-- 主要操作按钮区域 -->
      <div class="main-actions">
        <div class="action-card" @click="publishTask">
          <div class="action-icon">
            <i class="fas fa-plus-circle"></i>
          </div>
          <h3>发布任务</h3>
          <p>创建新的任务并发布</p>
        </div>
        
        <div class="action-card" @click="browseTasks">
          <div class="action-icon">
            <i class="fas fa-search"></i>
          </div>
          <h3>浏览任务</h3>
          <p>查看所有可接取的任务</p>
        </div>
        
        <div class="action-card" @click="myPublishedTasks">
          <div class="action-icon">
            <i class="fas fa-tasks"></i>
          </div>
          <h3>我发布的</h3>
          <p>管理您发布的任务</p>
        </div>
        
        <div class="action-card" @click="myAcceptedTasks">
          <div class="action-icon">
            <i class="fas fa-clipboard-list"></i>
          </div>
          <h3>我接取的</h3>
          <p>管理您接取的任务</p>
        </div>
      </div>
      
      <!-- 待接取任务区域 -->
      <div class="available-tasks-section">
        <div class="section-header">
          <h2><i class="fas fa-list"></i> 待接取任务</h2>
          <button @click="browseTasks" class="view-all-button">
            <span>查看全部</span>
            <i class="fas fa-arrow-right"></i>
          </button>
        </div>
        
        <div v-if="loadingTasks" class="loading">加载中...</div>
        
        <div v-else-if="availableTasks.length === 0" class="no-tasks">
          <i class="fas fa-inbox fa-2x"></i>
          <p>暂无待接取任务</p>
        </div>
        
        <div v-else class="tasks-grid">
          <div 
            v-for="task in availableTasks.slice(0, 4)" 
            :key="task.taskId" 
            class="task-card"
          >
            <div class="task-header">
              <h3>{{ task.title }}</h3>
              <span class="budget">¥{{ task.budget }}</span>
            </div>
            
            <div class="task-content">
              <p class="task-description">{{ task.description }}</p>
              <div class="task-meta">
                <div class="meta-item">
                  <i class="fas fa-calendar"></i>
                  <span>{{ formatDate(task.publishDate) }}</span>
                </div>
              </div>
            </div>
            
            <div class="task-actions">
              <button @click="acceptTask(task.taskId)" class="accept-button">
                <i class="fas fa-handshake"></i>
                <span>接取任务</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../api/index.js'

const router = useRouter()
const user = ref({})
const userMenuVisible = ref(false)
const availableTasks = ref([])
const loadingTasks = ref(false)

// 获取当前用户信息
const fetchCurrentUser = async () => {
  try {
    const response = await api.get('/user/current')
    if (response.code === 0) {
      user.value = response.data
    } else {
      // 用户未登录，跳转到登录页
      router.push('/login')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    router.push('/login')
  }
}

// 获取待接取任务
const fetchAvailableTasks = async () => {
  loadingTasks.value = true
  try {
    const response = await api.get('/task/all')
    if (response.code === 0) {
      availableTasks.value = response.data
    }
  } catch (error) {
    console.error('获取待接取任务失败:', error)
  } finally {
    loadingTasks.value = false
  }
}

// 发布任务
const publishTask = () => {
  router.push('/publish-task')
}

// 浏览任务
const browseTasks = () => {
  router.push('/browse-tasks')
}

// 我发布的任务
const myPublishedTasks = () => {
  router.push('/my-published-tasks')
}

// 我接取的任务
const myAcceptedTasks = () => {
  router.push('/my-accepted-tasks')
}

// 管理个人信息
const manageProfile = () => {
  router.push('/profile')
}

// 管理用户（仅管理员可见）
const manageUsers = () => {
  router.push('/users')
}

// 接取任务
const acceptTask = async (taskId) => {
  try {
    const response = await api.post(`/task/accept/${taskId}`)
    if (response.code === 0) {
      // 从列表中移除已接取的任务
      const index = availableTasks.value.findIndex(t => t.taskId === taskId)
      if (index !== -1) {
        availableTasks.value.splice(index, 1)
      }
      
      // 显示成功消息
      alert('任务接取成功！')
    } else {
      alert('接取任务失败: ' + response.message)
    }
  } catch (error) {
    console.error('接取任务失败:', error)
    alert('接取任务失败，请重试')
  }
}

// 切换用户菜单显示
const toggleUserMenu = () => {
  userMenuVisible.value = !userMenuVisible.value
}

// 点击其他地方隐藏菜单
const handleClickOutside = (event) => {
  if (userMenuVisible.value && !event.target.closest('.user-info')) {
    userMenuVisible.value = false
  }
}

// 用户登出
const handleLogout = async () => {
  userMenuVisible.value = false
  try {
    const response = await api.post('/user/logout')
    if (response.code === 0) {
      // 清除本地存储的用户信息
      localStorage.removeItem('user')
      router.push('/login')
    } else {
      alert('登出失败')
    }
  } catch (error) {
    console.error('登出失败:', error)
    alert('登出失败，请重试')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取当前日期
const getCurrentDate = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[date.getDay()]
  return `${year}年${month}月${day}日 ${weekday}`
}

onMounted(() => {
  fetchCurrentUser()
  fetchAvailableTasks()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.dashboard-wrapper {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
}

.dashboard-container {
  width: 100%;
  max-width: none;
  min-height: calc(100vh - 40px);
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  padding: 0;
  margin: 0 auto;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

/* 顶部导航栏 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.dashboard-header h1 {
  font-size: 28px;
  font-weight: 700;
  margin: 0;
}

.header-right {
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 20px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 10px;
}

.username {
  margin-right: 8px;
  font-weight: 500;
}

.user-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  width: 200px;
  z-index: 100;
  margin-top: 10px;
  overflow: hidden;
  animation: slideDown 0.3s ease;
  border: 1px solid #eee;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #667eea;
  color: white;
}

.menu-item:first-child {
  border-bottom: 1px solid #eee;
}

.menu-item i {
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.welcome-section {
  padding: 30px;
  text-align: center;
  background: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
}

.welcome-section h2 {
  color: #333;
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 700;
}

.welcome-section p {
  color: #666;
  font-size: 18px;
  margin: 0;
}

/* 主要操作按钮区域 */
.main-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 25px;
  padding: 30px;
  background: #f8f9fa;
}

.action-card {
  background: white;
  border-radius: 12px;
  padding: 30px 20px;
  text-align: center;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid #eee;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
  border-color: #667eea;
}

.action-icon {
  font-size: 40px;
  margin-bottom: 20px;
  color: #667eea;
}

.action-card:nth-child(2) .action-icon {
  color: #4facfe;
}

.action-card:nth-child(3) .action-icon {
  color: #43e97b;
}

.action-card h3 {
  font-size: 20px;
  margin-bottom: 10px;
  color: #333;
}

.action-card p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

/* 待接取任务区域 */
.available-tasks-section {
  padding: 0 30px 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  color: #333;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.section-header h2 i {
  margin-right: 10px;
  color: #667eea;
}

.view-all-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.view-all-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(102, 126, 234, 0.3);
}

.tasks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.task-card {
  border: 1px solid #eee;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
  background: #fff;
}

.task-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.task-header h3 {
  color: #333;
  font-size: 18px;
  margin: 0;
  flex: 1;
  margin-right: 10px;
}

.budget {
  font-weight: 700;
  color: #43e97b;
  background: rgba(67, 233, 123, 0.1);
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 14px;
}

.task-content {
  margin-bottom: 20px;
}

.task-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  white-space: pre-wrap;
  word-break: break-word;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.task-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #999;
  font-size: 14px;
}

.meta-item i {
  font-size: 12px;
}

.task-actions {
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.accept-button {
  width: 100%;
  padding: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.accept-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.accept-button i {
  font-size: 16px;
}

.no-tasks {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.no-tasks i {
  margin-bottom: 15px;
  color: #ddd;
}

.loading {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .header-left, .header-right {
    width: 100%;
    text-align: center;
  }
  
  .user-menu {
    right: auto;
    left: 50%;
    transform: translateX(-50%);
  }
  
  .main-actions {
    grid-template-columns: 1fr;
  }
  
  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .tasks-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 1200px) {
  .dashboard-container {
    padding: 25px;
  }
  
  .main-actions {
    gap: 15px;
    padding: 20px;
  }
  
  .action-card {
    padding: 20px 15px;
  }
  
  .action-icon {
    font-size: 32px;
    margin-bottom: 15px;
  }
  
  .action-card h3 {
    font-size: 18px;
  }
}

@media (max-width: 992px) {
  .dashboard-content {
    gap: 25px;
  }
  
  .content-section {
    min-width: 300px;
  }
  
  .task-actions, .management-actions {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 15px;
  }
  
  .action-button {
    padding: 20px 10px;
    min-height: 100px;
  }
  
  .action-button i {
    font-size: 28px;
  }
}

@media (max-width: 768px) {
  .dashboard-wrapper {
    padding: 15px;
  }
  
  .dashboard-container {
    padding: 20px;
  }
  
  .dashboard-header h1 {
    font-size: 28px;
  }
  
  .dashboard-header p {
    font-size: 18px;
  }
  
  .dashboard-content {
    flex-direction: column;
  }
  
  .content-section {
    min-width: 100%;
  }
  
  .task-actions, .management-actions {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .action-button {
    padding: 15px 5px;
    min-height: 90px;
    font-size: 14px;
  }
  
  .action-button i {
    font-size: 24px;
    margin-bottom: 8px;
  }
}

@media (max-width: 480px) {
  .task-actions, .management-actions {
    grid-template-columns: 1fr;
  }
  
  .action-button {
    padding: 15px 5px;
    min-height: 90px;
    font-size: 14px;
  }
  
  .action-button i {
    font-size: 24px;
    margin-bottom: 8px;
  }
}
</style>